import * as commonUtil from '@/api/utils/common';
import {
	decrypt
} from '@/api/utils/secret.js'
import {
	unzip
} from '@/api/utils/compress.js'

import {
	errorCode
} from '@/api/utils/errorCode.js';
import md5 from 'md5';
let timeout = 10000; //默认超时事件
let toast = commonUtil.toast;
//获取环境BASE_URL
const BASE_URL = process.env.BASE_URL == undefined ? '' : process.env.BASE_URL;
export const request = config => {
	console.log(commonUtil.ORIGIN_HEADER)
	//获取源请求头
	let header = uni.getStorageSync(commonUtil.ORIGIN_HEADER);

	//设置请求头
	if (!header) {
		toast("请求头不完整!")
		return;
	}

	config.header = header;
	//config.header['deviceId'] = '77aa3f97cc1be1f60cb74c5fcb6bde7b';


	// 设置token
	let authToken = "";
	uni.getStorage({
		key: commonUtil.AUTH_TOKEN_KEY,
		success: (resp) => {
			authToken = resp.data;
		}
	})
	config.header[commonUtil.AUTH_TOKEN_KEY] = authToken;

	let ts = new Date().getTime();
	config.header['ts'] = ts;
	let signStr = sign(config.url, header.deviceId, ts);
	config.header['sign'] = signStr;
	config.header['accesskey'] = 't3zsy2';
	//设置请求url
	let url = (BASE_URL != null && BASE_URL !== "") ? BASE_URL + config.url : config.url;
	// get请求映射params参数
	if (config.params) {
		url += '?' + tansParams(config.params)
		url = url.slice(0, -1)
	}
	config.url = url
	console.log("请求地址:" + config.url + ",当前运行环境 platform =" + uni.getSystemInfoSync().platform)
	return new Promise((resolve, reject) => {
		uni.request({
				method: config.method || 'get',
				timeout: config.timeout || timeout,
				url: config.url,
				data: config.data,
				header: config.header,
				dataType: 'json'
			}).then(response => {
				// console.log("响应结果：" + JSON.stringify(response))
				// #ifdef VUE3
				//vue3时编译的代码块
				if (response.statusCode != 200) {
					toast('后端接口连接异常')
					reject('后端接口连接异常')
					return
				}

				// #endif
				let res = response.data
				const code = res.code || 200
				const msg = errorCode[code] || res.msg
				if (code === 500) {
					toast(msg ? msg : "系统异常!")
					reject('500')
				} else if (code == 1013) {
					toast("请重新登录")
					reject('500')
				} else if (code !== 200) {
					toast(msg)
					reject(code)
				}
				//解密
				if (res.data) {
					let bb = decrypt(res.data);
					if (bb != '') {
						res.data = unzip(bb);
					} else {
						res.data = null;
					}
				}
				resolve(res.data || res)
			})
			.catch(error => {
				let {
					message
				} = error
				if (message === 'Network Error') {
					message = '后端接口连接异常'
				} else if (message.includes('timeout')) {
					message = '系统接口请求超时'
				} else if (message.includes('Request failed with status code')) {
					message = '系统接口' + message.substr(message.length - 3) + '异常'
				} else {
					toast('系统异常!请稍后再试')
					reject(error);
					return;
				}
				toast(message)
				reject(error)
			})
	})
}

const sign = (url, deviceId, ts) => {
	let paramsArray = [];
	let paramsIndex = url.indexOf("?");
	if (paramsIndex !== -1) {
		let str = url.substring(paramsIndex + 1, url.length);
		let strs = str.split("&");
		for (let i = 0; i < strs.length; i++) {
			let key = strs[i].substring(0, strs[i].indexOf("="));
			let value = strs[i].substring(strs[i].indexOf("=") + 1, strs[i].length);
			paramsArray.push(key + value)
		}
	}
	paramsArray.sort();

	let appendStr = url + paramsArray.join("")
	let md5key = md5('5sd2r5t2d');
	appendStr = appendStr + md5key + ts + deviceId;
	let finalStr = md5(appendStr).toLowerCase();
	return finalStr + '0a';

}




/**
 * 参数处理
 * @param params 参数
 */
const tansParams = (params) => {
	let result = ''
	for (const propName of Object.keys(params)) {
		const value = params[propName]
		var part = encodeURIComponent(propName) + "="
		if (value !== null && value !== "" && typeof(value) !== "undefined") {
			if (typeof value === 'object') {
				for (const key of Object.keys(value)) {
					if (value[key] !== null && value[key] !== "" && typeof(value[key]) !== 'undefined') {
						let params = propName + '[' + key + ']'
						var subPart = encodeURIComponent(params) + "="
						result += subPart + encodeURIComponent(value[key]) + "&"
					}
				}
			} else {
				result += part + encodeURIComponent(value) + "&"
			}
		}
	}
	return result
}